import React, { useEffect, useMemo, useState } from "react"
import Page from "@/components/page"
import { Input, View, Text, PageContainer } from "@tarojs/components"
import categorys from "@/store/categorys"
import { observer } from "mobx-react"
import account from "@/store/account"
import viewMode from "@/store/viewMode"
import { categoryType } from "@/types"
import iconClassNames from "@/styles/iconClassNames"
import http from "@/request"
import { ShowLoading, ShowToast, VibrateShort } from "@/utils"
import Taro from "@tarojs/taro"
import PageNav from "@/components/pageNav"

import "./index.scss"

const CategoryPage: React.FC = observer(() => {

    const [formVisible, setFormVisible] = useState(false)
    const [categoryItem, setCategoryItem] = useState<categoryType>()

    const categorysObj = useMemo(() => {
        return {
            default: (categorys.categoryList || []).filter(item => { return !item.isPersonal }),
            custom: (categorys.categoryList || []).filter(item => { return item.isPersonal }),
            maxSort: Math.max(...categorys.categoryList.map(item => { return item.sortIndex || 0 }))
        }
    }, categorys.categoryList)

    const saveCategory = () => {
        VibrateShort()
        http.post('/category/updateOrAdd', {
            ...categoryItem,
            accountId: account.activeAccount?.id
        }).then(_ => {
            setFormVisible(false)
            categorys.doUpDateCategorys()
        }).catch(err => {
            ShowToast(err.msg || '增加分类失败')
        })
    }

    const openEdit = (item: categoryType) => {
        setCategoryItem({
            ...item,
            sortIndex: categorysObj.maxSort + 1
        })
        setFormVisible(true)
    }

    const deleteCategory = () => {
        VibrateShort()
        Taro.showModal({
            title: `是否删除该分类？`,
            content: `删除后，【${categoryItem?.name}】下的账单将被归为“其他收支”`,
            success: (res: any) => {
                if (res.confirm) {
                    ShowLoading()
                    http.delete(`/category/delete/${categoryItem?.id}`).then(() => {
                        ShowToast("删除成功")
                        categorys.doUpDateCategorys()
                        setFormVisible(false)
                    }).catch(err => {
                        ShowToast(err.msg || '删除失败')
                    })
                }
            }
        })
    }

    useEffect(() => {
        viewMode.setBehind(formVisible)
    }, [formVisible])

    Taro.useDidHide(() => {
        setFormVisible(false)
    })

    return (
        <Page className="category-page page-background text-main-color">
            <PageNav showBack className="report-page-header need-filter">分类管理</PageNav>
            <View className="content-card need-filter card-background">
                <View className="item-title font-size24 flex-row">
                    <Text className="flex1">默认分类</Text>
                    <Text>默认分类暂时不可调整</Text>
                </View>
                <View className="flex-row flex-warp">
                    {
                        categorysObj.default.map(item => {
                            return <View className={`btn-item flex-column flex-center ${item.id === categoryItem?.id ? 'active' : ''}`}
                                key={item.id}>
                                <View className="icon-container flex-column flex-center">
                                    <View className="icon-bg"></View>
                                    <Text className={`iconfont ${item.iconClass}`}></Text>
                                </View>
                                <View className="icon-name font-size20">{item.name}</View>
                            </View>
                        })
                    }
                </View>
            </View>
            <View className="content-card need-filter card-background">
                <View className="item-title font-size24 flex-row">
                    <Text className="flex1">{account.activeAccount?.name}的自定义分类</Text>
                    <Text>点击管理分类</Text>
                </View>
                <View className="flex-row flex-warp">
                    {
                        categorysObj.custom.map(item => {
                            return <View className={`btn-item flex-column flex-center ${item.id === categoryItem?.id ? 'active' : ''}`}
                                onClick={() => openEdit(item)}
                                key={item.id}>
                                <View className="icon-container flex-column flex-center">
                                    <View className="icon-bg"></View>
                                    <Text className={`iconfont ${item.iconClass}`}></Text>
                                </View>
                                <View className="icon-name font-size20">{item.name}</View>
                            </View>
                        })
                    }
                    <View className="btn-item flex-column flex-center edit-btn" onClick={() => openEdit({})}>
                        <View className="icon-container flex-column flex-center">
                            <View className="icon-bg"></View>
                            <Text className="iconfont icon-shezhi"></Text>
                        </View>
                        <View className="icon-name font-size20">添加分类</View>
                    </View>
                </View>
            </View>
            <PageContainer show={formVisible} onLeave={() => setFormVisible(false)} overlay round zIndex={9999}>
                <View className="category-form-container font-size24 flex-column flex-item card-background">
                    <View className="form-item-container flex-row flex-item" style={{ width: '650rpx' }}>
                        <View className="btn-item selected-item flex-column flex-center">
                            <View className="icon-container flex-column flex-center">
                                <View className="icon-bg"></View>
                                <Text className={`iconfont ${categoryItem?.iconClass}`}></Text>
                            </View>
                        </View>
                        <View className="bottom-line flex1">
                            <Input className="form-input"
                                placeholder-class="placeholder-style"
                                maxlength={4}
                                placeholder="请输入分类名称"
                                value={categoryItem?.name || ''}
                                onInput={(e) => setCategoryItem({
                                    ...categoryItem,
                                    name: e.detail.value
                                })}></Input>
                        </View>
                    </View>
                    <View className="list-title-container flex-row flex-item">
                        <View className="list-title flex1">选择分类的图标</View>
                        {
                            categoryItem?.id ? <View className="delete-btn" onClick={deleteCategory}>
                                <Text className="iconfont icon-base-del"></Text>
                                <Text>删除分类</Text>
                            </View> : null
                        }
                    </View>
                    <View className="form-item-container flex-row flex-warp">
                        {
                            iconClassNames.map(item => {
                                return <View onClick={() => setCategoryItem({
                                    ...categoryItem,
                                    iconClass: item
                                })} className={`btn-item flex-column flex-center ${categoryItem?.iconClass === item ? 'active' : ''}`}
                                    key={item}>
                                    <View className="icon-container flex-column flex-center">
                                        <View className="icon-bg"></View>
                                        <Text className={`iconfont ${item}`}></Text>
                                    </View>
                                </View>
                            })
                        }
                    </View>
                </View>
                <View className="page-bottom flex-column flex-item card-background">
                    <View className="half-line"></View>
                    <View className="comment-input-container flex-row flex-item">
                        <View className="flex1"></View>
                        <View onClick={() => setFormVisible(false)} className="btn preview-btn flex-row flex-center">
                            <Text className="data-val font-size24">取消</Text>
                        </View>
                        <View className="flex1"></View>
                        <View onClick={saveCategory} className="btn save-btn flex-row flex-center">
                            <Text className="data-val font-size24">保存分类</Text>
                        </View>
                        <View className="flex1"></View>
                    </View>
                </View>
            </PageContainer>
        </Page>
    )
})
export default CategoryPage